package com.yanggu.bigdata.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import com.yanggu.bigdata.entity.vo.SugarResponse;
import com.yanggu.bigdata.service.ProductStatsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/sugar")
public class SugarController {

    @Autowired
    private ProductStatsService productStatsService;

    /**
     * 获取某一天的gmv, 默认为今天
     *
     * @param date
     * @return
     */
    @GetMapping("gmv")
    public SugarResponse<BigDecimal> getGMV(@RequestParam(defaultValue = "0") Integer date) {
        //如果是0, 即为默认值, 重新赋值为今天
        if (date == 0) {
            date = now();
        }
        BigDecimal gmv = productStatsService.getGMV(date);
        return SugarResponse.success(gmv);
    }

    /*
    {
        "status":0,
        "data":{
            "columns":[
                {
                    "name":"商品名称",
                    "id":"spu_name"
                },
                {
                    "name":"交易额",
                    "id":"order_amount"
                }
            ],
            "rows":[
                {
                    "spu_name":"小米 10",
                    "order_amount":"863399.00"
                },
                {
                    "spu_name":"iPhone11",
                    "order_amount":"548399.00"
                }
            ]
        }
     }
    */
    /**
     * 统计某天不同 SPU 商品交易额排名
     * @param date
     * @param limit
     * @return
     */
    @GetMapping("spu")
    public SugarResponse<Map<String, List<JSONObject>>> getProductStatsGroupBySpu(@RequestParam(defaultValue = "0") Integer date,
                                                                                  @RequestParam(defaultValue = "10") int limit) {
        //如果是0, 即为默认值, 重新赋值为今天
        if (date == 0) {
            date = now();
        }
        Map<String, List<JSONObject>> data = productStatsService.getProductStatsGroupBySpu(date, limit);
        return SugarResponse.success(data);
    }

    @GetMapping("/category3")
    private Integer now() {
        return Integer.parseInt(DateUtil.format(new Date(), "yyyyMMdd"));
    }

}
